import wx
import feedparser
import AGdb
import AGdialogs


class PRSS(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        
        framebox = wx.BoxSizer(wx.VERTICAL)        #Top frame box
        splitbox = wx.BoxSizer(wx.HORIZONTAL)      #left side and right side
        treebox = wx.BoxSizer(wx.VERTICAL)         # contains only the tree for sizing
        buttonbox = wx.BoxSizer(wx.HORIZONTAL)     # will hold the buttons on bottom 

        treepanel = wx.Panel(self, -1)             # left side tree view
        infopanel = wx.Panel(self, -1)             # right side info window

        PRSS.tree = wx.TreeCtrl(treepanel, 1, wx.DefaultPosition, (-1,-1), wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS)

        treefont = wx.Font(10,wx.DEFAULT,wx.DEFAULT,wx.DEFAULT)
        PRSS.tree.SetFont(treefont)

        PRSS.root = PRSS.tree.AddRoot('Feeds')
        feeds = []

        dbc=AGdb.rss_feeds.select()

        for result in list(dbc):
            feeds.append(PRSS.tree.AppendItem(PRSS.root, result.name))
            PRSS.tree.SetItemBold(feeds[len(feeds)-1],True)
            temp = {}
            temp = eval(result.data)

            for i in temp['entries']:
                PRSS.tree.AppendItem(feeds[len(feeds)-1], i['title'] )

        # feed 

        PRSS.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=1)
        self.display = wx.StaticText(infopanel, -1, '',(20,30), style=wx.ALIGN_CENTRE)

        # buttonbox 
        
        buttonbox.Add(wx.Button(self,201,"Refresh All"),1,wx.EXPAND)
        buttonbox.Add(wx.Button(self,202,"Add"),1,wx.EXPAND)
        buttonbox.Add(wx.Button(self,203,"Edit"),1,wx.EXPAND)
        buttonbox.Add(wx.Button(self,204,"Delete"),1,wx.EXPAND)

        self.Bind(wx.EVT_BUTTON, self.OnRefresh, id=201)
        self.Bind(wx.EVT_BUTTON, self.OnAdd, id=202)
        self.Bind(wx.EVT_BUTTON, self.OnEdit, id=203)
        self.Bind(wx.EVT_BUTTON, self.OnDelete, id=204)

        # frame layout

        treebox.Add(PRSS.tree, 1, wx.EXPAND)
        splitbox.Add(treepanel, 2, wx.EXPAND | wx.ALL,2)
        splitbox.Add(infopanel, 1, wx.EXPAND | wx.ALL,2)
        treepanel.SetSizer(treebox)

        framebox.Add(splitbox,1,wx.EXPAND)
        framebox.Add(buttonbox,0,wx.ALIGN_BOTTOM | wx.EXPAND | wx.ALL, 3)
        self.SetSizer(framebox)


    def OnSelChanged(self, event):
        item =  event.GetItem()
        self.display.SetLabel(self.tree.GetItemText(item))

    def OnRefresh(self, event):
        dbc=AGdb.rss_feeds.select()

        # das is eigentlich schlecht , lies unten
        PRSS.tree.DeleteAllItems()
        PRSS.root = PRSS.tree.AddRoot('Feeds')
        
        for result in list(dbc):
            feed = feedparser.parse( result.url )
            # TODO: error handling bevor man in die datanbank schreibt um alten daten nicht zu verlieren
            # interessant waer auch das es nicht total stirbt sonder den feed als error makiert
            result.data = repr(feed)
            temp = PRSS.tree.AppendItem(PRSS.root, result.name)
            PRSS.tree.SetItemBold(temp,True)
            for i in feed['entries']:
                PRSS.tree.AppendItem(temp, i['title'] )
                

    def OnAdd(self,event):
        dlg = RSSadd(self, -1,'Add Rss Feed')

    def OnEdit(self,event):
        dlg2 = RSSedit(self, -1,'Edit Rss Feed')

    def OnDelete(self,event):
        si = PRSS.tree.GetSelection()
        pi = PRSS.tree.GetItemParent(si)
        delete = pi 
        if ( PRSS.tree.GetItemText(pi) == 'Feeds' ):
            delete = si 
            
        dlg = AGdialogs.AGDelete(self,-1,'Delete RSS feed')
        dlg.text.SetLabel('Do you realy want to delete feed "' + PRSS.tree.GetItemText(delete) + '"')
        if dlg.ShowModal() == wx.ID_YES:
            dlg.Destroy()

            sqlfeed = AGdb.rss_feeds
            sqld = sqlfeed.select(sqlfeed.q.name==PRSS.tree.GetItemText(delete))
            sqld[0].destroySelf()
         
            PRSS.tree.Delete(delete)
            
        dlg.Destroy()
        
class RSSadd(wx.Dialog):
    def __init__(self,parent,id,title):
        wx.Dialog.__init__(self, parent, id , title)
                
        self.SetSize((500,170))
        wx.StaticText(self, -1, 'Name:',(30,20))
        wx.StaticText(self, -1, 'URL:',(30,50))
        self.name = wx.TextCtrl(self, -1, '', (100,17),(350,30))
        self.url = wx.TextCtrl(self, -1, '', (100,47),(350,30))
        self.cb = wx.CheckBox(self, -1, 'Use name from feed', (150, 85))
        
        wx.Button(self, 221, 'Add',(150,120))
        wx.Button(self, 222, 'Cancel',(260,120))

        self.Bind(wx.EVT_BUTTON, self.OnAdd, id=221)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, id=222)
        
        self.Center()
        self.ShowModal()
        self.Destroy()

    def OnAdd(self, event):

        # get url value from dialog window
        url = self.url.GetValue()
        # parse the feed
        feed = feedparser.parse( url )

        # use custome name or feed title 
        if ( self.cb.IsChecked() == True ):
            name = feed.feed.title
        else:
            name = self.name.GetValue()
            # if customname is empty and feed name not checked display error
            if (name == ""):
                # displayerror
                return
        
#        dbc=AniGrid.db.cursor()
        #dbc.execute("insert into rss_feeds (name,url,data) values (%s,%s,%s)",(name,url,repr(feed)))
        AGdb.rss_feeds(name=name,url=url,data=repr(feed))

        PRSS.tree.AppendItem(PRSS.root, name)
        PRSS.tree.SetItemBold(PRSS.tree.GetLastChild(PRSS.root),True)
        

        for i in feed.entries:
            PRSS.tree.AppendItem(PRSS.tree.GetLastChild(PRSS.root), i.title )
                  
        self.Close()


    def OnCancel(self, event):
        self.Close()


class RSSedit(wx.Dialog):
    def __init__(self,parent,id,title):
        wx.Dialog.__init__(self, parent, id , title)
        
        #TODO errorhandling if nothing is selected
        si = PRSS.tree.GetSelection()
        pi = PRSS.tree.GetItemParent(si)
        selected = pi 

        if ( PRSS.tree.GetItemText(pi) == 'Feeds' ):
            selected = si 

        sqlfeed = AGdb.rss_feeds
        sqld = sqlfeed.select(sqlfeed.q.name==PRSS.tree.GetItemText(selected))

        self.SetSize((500,170))
        wx.StaticText(self, -1, 'Name:',(30,20))
        wx.StaticText(self, -1, 'URL:',(30,50))
        self.name = wx.TextCtrl(self, -1, '', (100,17),(350,30))
        self.name.SetValue(sqld[0].name)
        self.url = wx.TextCtrl(self, -1, '', (100,47),(350,30))
        self.url.SetValue(sqld[0].url)
        self.cb = wx.CheckBox(self, -1, 'Use name from feed', (150, 85))
        
        wx.Button(self, 221, 'OK',(150,120))
        wx.Button(self, 222, 'Cancel',(260,120))

        self.Bind(wx.EVT_BUTTON, self.OnOk, id=221)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, id=222)
        
        self.Center()
        self.ShowModal()
        self.Destroy()

    def OnOk(self, event):
        # TODO
         self.Close()


    def OnCancel(self, event):
        self.Close()
